﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Controls;
using Douban.Core.HotKeys;
using System.Windows.Input;
using Douban.Core.Helpers;
using Douban.Core.Settings;
using Douban.Core.Messages;

namespace Douban
{
    public partial class MainWindow : IShellView
    {
        private ISettingManager _settingManager;
        private IMessageStack _messageStack;

        public MainWindow(ISettingManager settingManager, IMessageStack messageStack)
        {
            InitializeComponent();
            _settingManager = settingManager;
            _messageStack = messageStack;

            WindowPositionHelper.SetSize(this);
            this.Closing += (sender, e) =>
            {
                if (MessageBoxResult.No ==
                       MessageBox.Show(
                           Properties.Resources.QuitMessage,
                           Properties.Resources.QuitCaption,
                           MessageBoxButton.YesNo,
                           MessageBoxImage.Question))
                {
                    e.Cancel = true;
                }
                else
                {
                    DoubanNotifyIcon.Dispose();
                    WindowPositionHelper.Save(this);
                }
            };
        }

        private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var header = (Panel)this.FindName("PART_Header");
            if (header != null)
            {
                header.MouseLeftButtonDown += (trigger, args) => this.DragMove();
            }
            WindowDisplayHelper.GetInstance(this).Toggle();
            RegisterHotKeys();
        }

        private void RegisterHotKeys()
        {
            _settingManager.Register("GetMessageHotKey",
                (name, value) => RegisterHotKeys((HotKeySetting)value));

            RegisterHotKeys(_settingManager.Settings.GetMessageHotKey);
        }

        private void RegisterHotKeys(HotKeySetting hotKeySetting)
        {
            if (hotKeySetting == null || hotKeySetting.Modifiers == null) return;

            HotKey.Unregister(this, HotKeyIdentifiers.DisplayShell);

            ModifierKeys[] modifierKeys = hotKeySetting.Modifiers;
            ModifierKeys modifierKeyAccelators = ModifierKeys.None;
            foreach (var modifierKey in modifierKeys)
            {
                modifierKeyAccelators |= modifierKey;
            }

            HotKey.Register(
                this, HotKeyIdentifiers.DisplayShell, OnHotKeyTriggered, modifierKeyAccelators,
                hotKeySetting.Key);
        }

        private void OnHotKeyTriggered(HotKeyTriggeredEventArgs e)
        {
            if (HotKeyTriggered != null)
            {
                HotKeyTriggered(e);
            }

            if (e.Handled == false)
            {
                Debug.WriteLine("Toggle: HotKeyTriggered");
                if (!_messageStack.HasMessages())
                    Toggle();
                else
                    _messageStack.PopMessage();
            }
        }

        #region IShellView Members

        public IShellViewModel Context
        {
            get
            {
                return this.DataContext as IShellViewModel;
            } 
            set
            {
                this.DataContext = value;    
            }
        }

        public void ShowView()
        {
            Show();
            Activate();
        }

        public void CloseView()
        {
            this.Close();
        }

        public void Minimum()
        {
            DoubleAnimation minimumAnimation = new DoubleAnimation();
            minimumAnimation.To = 0;
            minimumAnimation.FillBehavior = FillBehavior.Stop;
            minimumAnimation.Duration = TimeSpan.FromMilliseconds(300);
            minimumAnimation.Completed += (sender, e) =>
            {
                this.WindowState = System.Windows.WindowState.Minimized;
                this.BeginAnimation(OpacityProperty, null);
            };

            this.BeginAnimation(OpacityProperty, minimumAnimation);
        }

        public void PromptAuthorization(Uri authorizationUrl)
        {
            Process.Start(authorizationUrl.ToString());

            AuthorizationPromptWindow promptWindow = new AuthorizationPromptWindow();
            promptWindow.Owner = this;
            promptWindow.Closed += promptWindow_Closed;
            promptWindow.ShowDialog();
        }

        private void promptWindow_Closed(object sender, EventArgs e)
        {
            var win = (AuthorizationPromptWindow)sender;
            if (!win.IsAuthorized)
            {
                MessageBox.Show("授权失败！请重新授权！");
                this.Close();
            }
        }

        public void NotifyAllModulesLoaded()
        {
            RaiseEvent(new RoutedEventArgs(AllModulesLoadedEvent, this));
        }

        public void Toggle()
        {
            WindowDisplayHelper.GetInstance(this).Toggle();
        }

        #endregion

        public event HotKeyTriggeredEventHandler HotKeyTriggered;
    }
}
